package me.zhengjie.modules.business.service.impl;

import me.zhengjie.modules.business.domain.AuthData;
import me.zhengjie.modules.business.domain.WxUser;
import me.zhengjie.modules.business.repository.WxUserRepository;
import me.zhengjie.modules.business.service.WxUserService;
import me.zhengjie.modules.business.service.dto.WxUserDto;
import me.zhengjie.modules.business.service.dto.WxUserQueryCriteria;
import me.zhengjie.modules.business.service.mapper.WxUserMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;

/**
* @author churuitao
* @date 2020-02-04
*/
@Service
//@CacheConfig(cacheNames = "wxUser")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class WxUserServiceImpl implements WxUserService {

    private final WxUserRepository wxUserRepository;

    private final WxUserMapper wxUserMapper;

    public WxUserServiceImpl(WxUserRepository wxUserRepository, WxUserMapper wxUserMapper) {
        this.wxUserRepository = wxUserRepository;
        this.wxUserMapper = wxUserMapper;
    }

    @Override
    //@Cacheable
    public Map<String,Object> queryAll(WxUserQueryCriteria criteria, Pageable pageable){
        Page<WxUser> page = wxUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(wxUserMapper::toDto));
    }

    @Override
    //@Cacheable
    public List<WxUserDto> queryAll(WxUserQueryCriteria criteria){
        return wxUserMapper.toDto(wxUserRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    //@Cacheable(key = "#p0")
    public WxUserDto findById(Integer id) {
        WxUser wxUser = wxUserRepository.findById(id).orElseGet(WxUser::new);
        ValidationUtil.isNull(wxUser.getId(),"WxUser","id",id);
        return wxUserMapper.toDto(wxUser);
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public WxUserDto create(WxUser resources) {
        return wxUserMapper.toDto(wxUserRepository.save(resources));
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(WxUser resources) {
        WxUser wxUser = wxUserRepository.findById(resources.getId()).orElseGet(WxUser::new);
        ValidationUtil.isNull( wxUser.getId(),"WxUser","id",resources.getId());
        wxUser.copy(resources);
        wxUserRepository.save(wxUser);
    }

    @Override
    //@CacheEvict(allEntries = true)
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            wxUserRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<WxUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (WxUserDto wxUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("头像", wxUser.getAvatar());
            map.put("邮箱", wxUser.getEmail());
            map.put("状态", wxUser.getEnabled());
            map.put("昵称", wxUser.getNickName());
            map.put("性别", wxUser.getSex());
            map.put("微信小程序id", wxUser.getMiniOpenId());
            map.put("微信公众号id", wxUser.getOfficialOpenId());
            map.put("微信唯一标识", wxUser.getUnionId());
            map.put("所在地", wxUser.getLocation());
            map.put("用户定位", wxUser.getOrientation());
            map.put("认证资料id", wxUser.getAuthData());
            map.put("创建时间", wxUser.getCreateTime());
            map.put("更新时间", wxUser.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public boolean checkAuthStatus(int id) {
        WxUser wxUser = wxUserRepository.findById(id).orElseGet(WxUser::new);
        AuthData authData = wxUser.getAuthData();
        if(authData!=null){
            return authData.getStatus()==1?true:false;
        }
        return false;
    }

    public WxUserDto findWxUserByMiniOpenid(String openid){
        WxUser wxUser = wxUserRepository.findByMiniOpenId(openid);
        // 如果 openid 不存在新建一个
        if(wxUser==null){
            wxUser = new WxUser();
        }
        return wxUserMapper.toDto(wxUser);
    }



}